package com.tanhua.server.service;

import com.alibaba.fastjson.JSON;
import com.tanhua.autoconfig.templates.AipFaceTemplate;
import com.tanhua.autoconfig.templates.OssTemplate;
import com.tanhua.autoconfig.templates.SmsTemplate;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.vo.ErrorResult;
import com.tanhua.domain.vo.UserInfoVo;
import com.tanhua.dubbo.api.UserApi;


import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.utils.JwtUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.Duration;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {


    @Reference
    private UserApi userApi;
    @Reference
    private UserInfoApi userInfoApi;
    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    //保存头像
    public ResponseEntity updateheader(MultipartFile headPhoto) throws IOException {
        User user = UserHolder.getUser();
        String url = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        UserInfo userinfo = userInfoApi.findById(user.getId());
        userinfo.setAvatar(url);
        userInfoApi.update(userinfo);
        return ResponseEntity.ok(null);
    }

    //更新用户信息
    public ResponseEntity updateUserInfo(UserInfo userInfo) {
        //1.获取id
        User user = UserHolder.getUser();
        Long id=user.getId();
        //2.设置到userinfo对象里面
        userInfo.setId(id);
        //3.更新
        userInfoApi.update(userInfo);
        //4.返回数据
        return ResponseEntity.ok(null);

        /*2.给userinfo进行赋值
        代码正常 就是啰嗦 要简化版本
        UserInfo userInfo1 = userInfoApi.findById(user.getId());
        userInfo1.setNickname(userInfo.getNickname());
        userInfo1.setBirthday(userInfo.getBirthday());
        userInfo1.setGender(userInfo.getGender());
        userInfo1.setCity(userInfo.getCity());
        userInfo1.setIncome(userInfo.getIncome());
        userInfo1.setEducation(userInfo.getEducation());
        userInfo1.setProfession(userInfo.getProfession());
        userInfo1.setMarriage(userInfo.getMarriage());
        userInfoApi.update(userInfo1);*/

    }

    //查询当前操作用户的信息
    public ResponseEntity findUserInfo() {
        //1.user的id就是userinfo的id 所以首先获取id
        User user = UserHolder.getUser();
        //2.根据id查询userinfo
        UserInfo userInfo=userInfoApi.findById(user.getId());
        //3.将userinfo转化为userinfovo
        UserInfoVo userInfoVo=new UserInfoVo();
        //功能非常强大 自动将userinfo里面的同名同类型属性赋值到userinfovo里面
        BeanUtils.copyProperties(userInfo,userInfoVo);
        userInfoVo.setAge(userInfo.getAge()==null?"18":userInfo.getAge().toString());
        //3.构建返回值
        return ResponseEntity.ok(userInfoVo);
    }


    //更新用户逻辑 里面调用百度人脸识别和阿里云OSS对象存储
    public  ResponseEntity updateUserHead( MultipartFile headPhoto) throws IOException {
        //1.首先判断图片是否包含人脸 用boolean接收一下
        boolean detect = aipFaceTemplate.detect(headPhoto.getBytes());
        if (!detect){
            //如果图片没有包含人脸就报错
            return ResponseEntity.status(500).body(ErrorResult.faceError());
        }
        //2.如果包含人脸 需要上传到阿里云oss 获取请求url
        String url = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //3.开始更新用户信息
        //3.1获取当前操作的用户对象(user,用户的id就是userinfo的id)
        User user = UserHolder.getUser();
        //3.2根据Id查询userinfo
        UserInfo userInfo=userInfoApi.findById(user.getId());
        //3.3设置头像
        userInfo.setAvatar(url);
        //3.4更新头像?
        userInfoApi.update(userInfo);
        //4.构建返回值
        return ResponseEntity.ok(null);
    }

    //对手机号码发送验证码
    public ResponseEntity sendMsg(String mobile) {
        //生成验证码 6位数字 调用工具类生成验证码
        String code = RandomStringUtils.randomAlphabetic(6);

        code="123456";
        //调用smsTemplate发送
        //smsTemplate.sendSms(mobile,code);

        //存入redis
        //第一个是名字 第二个是验证码数据 第三个是失效时间
        redisTemplate.opsForValue().set("CHECK_CODE"+mobile,code, Duration.ofMinutes(15));
        //构建返回值
        return ResponseEntity.ok(null);

    }

    // 对应的用户登录
    public ResponseEntity login(String phone, String verificationCode) {
        //1.获取Redis里面的验证码
        String code = redisTemplate.opsForValue().get("CHECK_CODE" + phone);
        //2.进行验证码的校验
        if (code==null||!code.equals(verificationCode)){
            //如果不一致 要给一个错误信息的
            //return ResponseEntity.status(500).body("验证码错误");
            return ResponseEntity.status(500).body(ErrorResult.logincode());
        }
        redisTemplate.delete("CHECK_CODE" + phone);

        //3.根据手机号去数据库里面进行查询是否存在该账户
        User user = userApi.findByMobile(phone);
        //3.1如果用户不存在的话进行创建
        Boolean isNew=false;
        if (user==null){
            user=new User();
            user.setUpdated(new Date());
            user.setCreated(new Date());
            user.setMobile(phone);
            user.setPassword("123456");
            Long id = userApi.save(user);
            user.setId(id);
            isNew=true;
        }
        //3.2生成token
        String token = JwtUtils.createToken(phone, user.getId());

        //4.1将对象转换成json的形式
        String jsonUser = JSON.toJSONString(user);
        //4.2数据存入Redis里面 设置失效时间
        redisTemplate.opsForValue().set("TOKEN"+token,jsonUser,Duration.ofHours(1));

        //5.构建返回值  返回值为token和isNew建立map集合
        Map map=new HashMap();
        map.put("isNew",isNew);
        map.put("token",token);
        return ResponseEntity.ok(map);
    }

    /**
     * 保存用户信息
     * token:用户信息的字符串
     * @param userInfo
     * @return
     */

    public ResponseEntity saveUserInfo(UserInfo userInfo) {
        //userinfo的id需要手动赋值,当前操作用户的id
        //获取当前操作的用户
        User user = UserHolder.getUser();
        //向userinfo当中设置id
        userInfo.setId(user.getId());
        userInfo.setUpdated(new Date());
        userInfo.setCreated(new Date());
        //调用userInfoApi保存用户信息
        userInfoApi.save(userInfo);
        //构造返回值
        return  ResponseEntity.ok(null);//200成功
    }


    public User getUserByToken(String token){
        String userStr = redisTemplate.opsForValue().get("TOKEN" + token);
        if (StringUtils.isEmpty(userStr)){
            return null;
        }else {
            return JSON.parseObject(userStr,User.class);
        }
    }



    public ResponseEntity findUser(String mobile) {
        User user = userApi.findByMobile(mobile);
        return ResponseEntity.ok(user);//正常

    }


    public ResponseEntity saveUser(User user) {

        user.setCreated(new Date());
        user.setUpdated(new Date());
        userApi.save(user);
        System.out.println(user.getId());
        return ResponseEntity.status(500).body("号码错了");

        /*userApi.save(user);*/
    }



}
